from typing import Dict, Any

from playwright.sync_api import Page

from service.ResDataService import get_end_data
from tools.Result import success_result, error_result
from service.StatusEnum import StatusEnum
from tools.HtmlPageService import get_selector_text, get_selector_href

# 全局存储响应数据（可根据需求调整）
response_data = {}


def handle_response(response):
    """响应处理器（带数据收集功能）"""
    global response_data
    # 记录所有响应URL

    if "queryRtRecyclingInfoById" in response.url:
        response_data["info"] = response.json()
    if "queryQuoteItemInfo" in response.url:
        response_data["list"] = response.json()


def get_html_detail(page: Page, detail_url: str) -> Dict[str, Any]:

    """获取页面详情并捕获响应数据"""
    global response_data
    # 清空历史数据
    response_data = {}
    # 设置响应监听器
    page.on("response", handle_response)
    try:
        page.goto(detail_url, wait_until="networkidle", timeout=15000)

        login_title = get_selector_text(page, ".titleLogin")

        if login_title == "请登录":
            auth_url = get_selector_href(page, ".titleLogin")


            if auth_url:

                page.goto(auth_url, wait_until="networkidle", timeout=15000)


                page.goto(detail_url, wait_until="networkidle", timeout=15000)


        # 返回收集到的响应数据
        return success_result("获取成功", get_result(response_data))

    except Exception as e:
        return error_result(f"页面加载失败: {str(e)}")


def get_result(data):
    # 安全获取list数据
    list_data = data.get("list", {}).get("data", []) if isinstance(data.get("list"), dict) else []
    current_price = list_data[0]["quoteValue"] if list_data else ""

    # 安全获取info数据
    info_data = data.get("info", {}).get("data", {}) if isinstance(data.get("info"), dict) else {}
    start_price = info_data.get("startPrice", "")
    status = info_data.get("status", -99)
    trade_type = info_data.get("tradeType", 0)
    if trade_type==1 and status==1:
        status = 2
    return get_end_data(start_price, current_price, StatusEnum.get_common_info(status))


